package org.lanlab.storode.service;

import org.lanlab.storode.dal.entity.Requirement;
import org.lanlab.storode.dal.entity.RequirementState;
import org.lanlab.storode.dal.repository.RequirementRepository;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author dove
 * @since 2020/1/10 10:49
 */
@Service
public class RequirementService {

    private final RequirementRepository requirementRepository;

    public RequirementService(RequirementRepository requirementRepository) {
        this.requirementRepository = requirementRepository;
    }

    public Requirement insertRequirement(Requirement requirement) {
        requirement.setVersion(1L);
        requirement.setState(RequirementState.INIT.getCode());
        requirement.setDeleted(false);
        requirement.setCreateTime(LocalDateTime.now());
        requirement.setUpdateTime(LocalDateTime.now());
        return requirementRepository.save(requirement);
    }

    public Requirement getRequirementByNo(String requirementNo) {
        return requirementRepository.findLatestVersion(requirementNo);
    }

    public boolean updateRequirement(Requirement requirement) {
        Requirement latestVersion = getRequirementByNo(requirement.getRequirementNo());
        if (Objects.nonNull(latestVersion)) {
            requirement.setVersion(latestVersion.getVersion() + 1L);
            requirement.setCreateTime(LocalDateTime.now());
            requirement.setUpdateTime(LocalDateTime.now());
            requirementRepository.save(requirement);
            return true;
        } else {
            return false;
        }
    }

    public boolean deleteRequirement(String requirementNo) {
        int count = requirementRepository.deleteAllByRequirementNo(requirementNo);
        return count > 0;
    }

    public List<Requirement> listAllRequirements() {
        return requirementRepository.findAllLatestRequirements();
    }
}
